package de.tto.dating.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.thoughtworks.xstream.XStream;

import de.tto.dating.constants.HTMLPage;
import de.tto.dating.entities.User;
import de.tto.dating.entities.UserDAO;
import de.tto.dating.utils.EmailService;
import de.tto.dating.utils.FileService;
import de.tto.dating.utils.UserSupport;
import de.tto.dating.validation.Validator;
import de.tto.dating.xml.StatusXML;

public class RegisterServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4794487386364261525L;

	// private static final Logger log = Logger.getLogger(RegisterServlet.class
	// .getName());

	private User user = null;

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		StatusXML status = new StatusXML();

		applyRequestValues(req);

		if (!processValidations(status)) {
			resp.getWriter().println(new XStream().toXML(status));
			return;
		}

		getUser().setConfirmKey(new UserSupport().generateConfirmKey());

		User savedUser = new UserDAO().save(getUser());
		if (savedUser == null) {
			status.setMain("Internal Error: Bitte versuchen Sie noch einmal!");
			resp.getWriter().println(new XStream().toXML(status));
			return;
		}

		new EmailService().sendAccountConfirmEmail(savedUser,
				getServletContext());
		String accConfirm = new FileService().readFile(getServletContext(),
				HTMLPage.ACCOUNT_CONFIRM);
		String userMailAccount = savedUser.getEmail();
		int atEndex = userMailAccount.indexOf("@");
		status.setMain(accConfirm.replace("#{email}", savedUser.getEmail())
				.replace("#{userMailAccount}",
						userMailAccount.substring(atEndex + 1)));
		resp.getWriter().println(new XStream().toXML(status));
	}

	private boolean processValidations(StatusXML status) {
		return (new Validator()).validateRegisterInput(getUser(), status);
	}

	private void applyRequestValues(HttpServletRequest req) {
		user = new User();
		user.setEmail(req.getParameter("email"));
		user.setPassword(req.getParameter("password"));
	}

	/**
	 * @param user
	 *            the user to set
	 */
	public void setUser(User user) {
		this.user = user;
	}

	/**
	 * @return the user
	 */
	public User getUser() {
		return user;
	}

}
